package com.sskj.gcc.ui.fragment;

import android.content.Context;
import android.content.Intent;
import android.text.InputFilter;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import com.hey.lib.HeySpinner;
import com.sskj.gocoin.MyAppLication;
import com.sskj.gocoin.R;
import com.sskj.gocoin.R2;
import com.sskj.gocoin.common.App;
import com.sskj.gocoin.common.Constants;
import com.sskj.gocoin.common.MoneyValueFilter;
import com.sskj.gocoin.m.bean.AseetListBean;
import com.sskj.gocoin.m.bean.CoinFeeBean;
import com.sskj.gcc.presenter.WithdrawPresenter;
import com.sskj.gocoin.utils.CheckUtil;
import com.sskj.gocoin.utils.ClickUtil;
import com.sskj.gocoin.utils.ToastUtil;
import com.sskj.gocoin.v.activity.CashAddressListActivity;
import com.sskj.lib.base.BaseFragment;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;

import butterknife.BindView;
import io.reactivex.Flowable;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.schedulers.Schedulers;
import io.reactivex.subscribers.DisposableSubscriber;

import static android.app.Activity.RESULT_OK;

/**
 * <pre>
 *     USDT提币
 *     author : 吕志豪
 *     e-mail : 1030753080@qq.com
 *     time   : 2018/04/03
 *     desc   :
 *     version: 1.0
 * </pre>
 */

public class WithdrawFragment extends BaseFragment<WithdrawPresenter> {

    @BindView(R2.id.et_address)
    EditText etAddress;
    @BindView(R2.id.iv_address)
    ImageView ivAddress;
    @BindView(R2.id.et_number)
    EditText etNumber;
    @BindView(R2.id.tv_all)
    TextView tvAll;
    @BindView(R2.id.view_line)
    View viewLine;
    @BindView(R2.id.et_password)
    EditText etPassword;
    @BindView(R2.id.bt_send_code)
    Button btSendCode;
    @BindView(R2.id.et_check_code)
    EditText etCheckCode;
    @BindView(R2.id.bt_withdraw)
    Button btWithdraw;
    @BindView(R2.id.tv_account)
    TextView mTvAccount;
    @BindView(R2.id.tv_max_num)
    TextView mTvMaxNum;
    @BindView(R2.id.tv_fee)
    TextView tvFee;
    @BindView(R2.id.recharge_hint)
    TextView tvRechargeHint;
    @BindView(R2.id.withdraw_unit)
    TextView tvWithdrawUnit;

    @BindView(R2.id.toolbar_left)
    TextView toolbarLeft;
    @BindView(R2.id.toolbar_center)
    HeySpinner toolbarCenter;

    private DisposableSubscriber<Long> disposableSubscriber;
    private Double minCoin = 0d;
    private Double maxCoin = 0d;
    private Double wallone;
    private String mTb_fee;


    private List<AseetListBean.AseetBean> assetBeans;
    private String assetName;
    private int assetId;


    @Override
    public int getLayoutId() {
        return R.layout.activity_withdraw;
    }

    @Override
    public WithdrawPresenter getPresenter() {
        return new WithdrawPresenter();
    }

    @Override
    public void initView() {
        ClickUtil.click(btSendCode, () -> {
            if (CheckUtil.isEmail(MyAppLication.getMobile())) {
                mPresenter.sendEmail();
            } else {
                mPresenter.sendCode();
            }
        });

        ClickUtil.click(ivAddress, () -> {
            startActivityForResult(new Intent(getContext(), CashAddressListActivity.class).putExtra(Constants.INTENT_CALL_BACK, true), Constants.CASH_ADDRESS);
        });

        tvRechargeHint.setText(App.INSTANCE.getString(com.sskj.gcc.R.string.app_withdrawFragment1) + assetName + App.INSTANCE.getString(R.string.strWithdrawActivity203) + assetName + App.INSTANCE.getString(R.string.strWithdrawActivity204));
        tvWithdrawUnit.setText(assetName);
        ClickUtil.click(btWithdraw, () -> {

            if (TextUtils.isEmpty(etAddress.getText())) {
                ToastUtil.showShort(App.INSTANCE.getString(R.string.strWithdrawActivity205));
                return;
            }
            if (TextUtils.isEmpty(etNumber.getText())) {
                ToastUtil.showShort(App.INSTANCE.getString(R.string.strWithdrawActivity206));
                return;
            }
            Double aDouble = Double.valueOf(etNumber.getText().toString());
            if (aDouble < minCoin) {
                ToastUtil.showShort(App.INSTANCE.getString(R.string.strWithdrawActivity207) + minCoin + App.INSTANCE.getString(R.string.strWithdrawActivity208));
                return;
            }

            if (aDouble > maxCoin) {
                ToastUtil.showShort(App.INSTANCE.getString(R.string.strWithdrawActivity209) + maxCoin + App.INSTANCE.getString(R.string.strWithdrawActivity208));
                return;
            }

            if (aDouble > wallone - Double.parseDouble(mTb_fee)) {
                ToastUtil.showShort(App.INSTANCE.getString(R.string.strWithdrawActivity211));
                return;
            }
            if (TextUtils.isEmpty(etPassword.getText())) {
                ToastUtil.showShort(App.INSTANCE.getString(R.string.strWithdrawActivity212));
                return;
            }

            if (TextUtils.isEmpty(etCheckCode.getText())){
                ToastUtil.showShort(etCheckCode.getHint());
                return;
            }

            mPresenter.withdraw(etNumber.getText().toString().trim(),
                    etPassword.getText().toString().trim(),
                    etCheckCode.getText().toString().trim(),
                    etAddress.getText().toString().trim(), assetId);
        });
        etNumber.setFilters(new InputFilter[]{new MoneyValueFilter().setDigits(4)});

    }

    @Override
    public void initData() {
        mPresenter.requestUserAssetList();
    }

    private void initSpinner() {
        List<String> data = new ArrayList<>();
        for (AseetListBean.AseetBean bean : assetBeans) {
            data.add(bean.pname);
        }
        toolbarCenter.attachData(data);
        toolbarCenter.setOnSelectListener(position -> {
            assetName = assetBeans.get(position).pname;
            assetId = assetBeans.get(position).pid;
        });
        toolbarCenter.setSelectIndex(0);
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK & requestCode == Constants.CASH_ADDRESS) {
            String address_url = data.getStringExtra("address_url");
            if (!TextUtils.isEmpty(address_url)) {
                etAddress.setText(address_url);
            }
        }
    }

    public void startCount() {
        btSendCode.setEnabled(false);
        disposableSubscriber = new DisposableSubscriber<Long>() {
            @Override
            public void onNext(Long aLong) {
                int time = (int) (60 - aLong);
                btSendCode.setText(time + App.INSTANCE.getString(R.string.strWithdrawActivity214));
            }

            @Override
            public void onError(Throwable t) {
                System.out.println(t.toString());
            }

            @Override
            public void onComplete() {
                btSendCode.setText(App.INSTANCE.getString(R.string.strWithdrawActivity215));
                btSendCode.setEnabled(true);
                if (!disposableSubscriber.isDisposed()) {
                    disposableSubscriber.dispose();
                    disposableSubscriber = null;
                }

            }
        };
        Flowable.interval(0, 1, TimeUnit.SECONDS, Schedulers.newThread())
                .take(60)
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(disposableSubscriber);
    }

    public void setCodeOk() {
//        btWithdraw.setEnabled(true);
    }

    public void updateCoin(CoinFeeBean data) {
        wallone = Double.valueOf(data.getBalance());
        mTb_fee = data.getTb_fee();
        mTvMaxNum.setText(App.INSTANCE.getString(R.string.strWithdrawActivity216) + data.getBalance());
        ClickUtil.click(tvAll, () -> {
            etNumber.setText(String.valueOf(wallone - Double.parseDouble(data.getTb_fee())));
        });
        minCoin = data.getTb_min();
        maxCoin = data.getTb_max();
        etNumber.setHint(App.INSTANCE.getString(R.string.strWithdrawActivity217) + data.getTb_min() + App.INSTANCE.getString(R.string.strWithdrawActivity218) + data.getTb_max() + assetName);
        tvFee.setText(String.format(App.INSTANCE.getString(R.string.strWithdrawActivity219), data.getTb_fee() + ""));
    }

    public static void start(Context context, List<AseetListBean.AseetBean> data) {
        Intent intent = new Intent(context, WithdrawFragment.class);
        intent.putExtra("data", (Serializable) data);
        context.startActivity(intent);
    }


    public void onDataSuccess(AseetListBean data) {
        Flowable.fromIterable(data.asset)
                .filter(aseetBean -> !aseetBean.pname.equals("GCT"))
                .toList()
                .subscribe(aseetBeans -> {
                    assetBeans = aseetBeans;
                    initSpinner();
                });
    }
}
